var db = require('../../utils/db/mysqlDb');
var common = require('../../utils/commonUtils');
var fansModel = require('../model/Fans');
var Promise = require('promise');
var FansDao = {};

FansDao.update = function(obj) {
	  var sql = 'update wechat_fans set ';
	    if(common.isNotBlank(obj.subscribe)){
	        sql+='fans_subscribe=:subscribe,';
	    }
	    if(common.isNotBlank(obj.nickname)){
	        sql+='fans_nickname=:nickname,';
	    }
	    if(common.isNotBlank(obj.sex)){
	        sql+='fans_sex=:sex,';
	    }
	    if(common.isNotBlank(obj.city)){
	        sql+='fans_city=:city,';
	    }
	    if(common.isNotBlank(obj.country)){
	        sql+='fans_country=:country,';
	    }
	    if(common.isNotBlank(obj.province)){
	        sql+='fans_province=:province,';
	    }
	    if(common.isNotBlank(obj.headImgUrl)){
	        sql+='fans_headimgurl=:headImgUrl,';
	    }
	    if(common.isNotBlank(obj.language)){
	        sql+='fans_language=:language,';
	    }
	    if(common.isNotBlank(obj.subscribeTime)){
	        sql+='fans_subscribe_time=:subscribeTime,';
	    }
	/*    if(obj.unionId != undefined){
	        sql+='union_id=:unionId,';
	    }*/
	    sql+='where fans_id=:id ';
	    sql = sql.replace(',where', ' where ');
	    return db.update(sql, obj);
	};

// 保存fans信息
FansDao.save = function(obj) {
	 return db.save('insert into wechat_fans set ? ',
			 fansModel.modelConvertDb(obj));
};

// 根据openid获取当前fans信息
FansDao.getByOpenId = function(openId) {
  return new Promise(function(fulfill, reject){
	 var sql =  'select * from wechat_fans where fans_openid ='+db.escape(openId);
	 db.query(sql).then(function(rows){
		 fulfill(fansModel.dbConvertModel(rows[0]));
	  },function(err){
		  reject(err);
	  });
  });
};

// 根据openid 获取fans统计
FansDao.countFansByOpenId = function(openid, callback) {
  dbUtils.query('select count(*) as total from wechat_fans where fans_openid = :openid' ,{openid: openid}, function(rows) {
    if (callback && rows[0]) {
      callback(rows[0].total);
    } else {
      callback(0);
    }
  });
};



// 更新粉丝关注信息
FansDao.updateSubscribe = function(subscribe, id, callback) {
  var sql = 'update wechat_fans set subscribe = :subscribe where id = :id';
  dbUtils.update(sql, {subscribe : subscribe, id : id}, function(rows) {
    if (callback) {
      callback(rows);
    }
  });
};

module.exports = FansDao;